'use client'

import { useState } from "react";
import { useRouter } from "next/navigation";

type EditTopicProps = {
    id: string;
    title: string;
    description: string;
}

export default function EditTopicForm({ id, title, description }: EditTopicProps) {
    const [newTitle, setNewTitle] = useState<string>(title);
    const [newDescription, setNewDescription] = useState<string>(description);

    const router = useRouter();

    const handleSubmit = async (e: any) => {
        e.preventDefault();

        try {
            const response = await fetch(`/api/topics/${id}`, {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ newTitle, newDescription }),
            });

            if (!response.ok) {
                throw new Error("Failed to update topic");
            }

            router.refresh();
            router.push("/");
        } catch (error) {
            console.error(error);
        }
    }

    return (
        <form onSubmit={handleSubmit} className="flex flex-col gap-3">
            <input
                onChange={(e: any) => setNewTitle(e.target.value)}
                value={newTitle}
                className="border border-slate-500 px-8 py-2"
                type="text"
                placeholder="Topic Title"
            />

            <input
                onChange={(e: any) => setNewDescription(e.target.value)}
                value={newDescription}
                className="border border-slate-500 px-8 py-2"
                type="text"
                placeholder="Topic Description"
            />

            <button className="bg-green-600 font-bold text-white py-3">
                Update Topic
            </button>
        </form>
    )
}